package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

//查询所有
//1.sql:select * from tb_brand
//2.参数：不需要
//3.结果：List<Brand>
public class BrandTest {
    public static void main(String[] args) throws Exception {
        //1.获取connection
        Properties properties = new Properties();
        properties.load(new FileInputStream("jdbc-demo/src/main/resources/druid.properties"));
        //4.获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        //5.获取对应的数据库连接
        Connection conn = dataSource.getConnection();
        //2.定义sql
        String sql = "select * from tb_brand ";
        //3.获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
        //4.设置参数
        //5.执行sql
        ResultSet rs = pstmt.executeQuery();
        //6.定义List<brand>处理结果 封装对象
        List<Brand> list = new ArrayList<>();
        Brand brand = null;
        while (rs.next()){
            //获取数据
            int id = rs.getInt("id");
            String brandName = rs.getString("brand_name");
            String companyName = rs.getString("company_name");
            int ordered = rs.getInt("ordered");
            String description = rs.getString("description");
            int status = rs.getInt("status");
            //封装brand对象
            brand = new Brand();
            brand.setId(id);
            brand.setBrandName(brandName);
            brand.setCompanyName(companyName);
            brand.setOrdered(String.valueOf(ordered));
            brand.setDescription(description);
            brand.setStatus(status);
            //封装集合
            list.add(brand);
        }
        System.out.println(list);
        //7.释放资源
        rs.close();
        pstmt.close();
        conn.close();
    }
}
